package com.lly.bigdata.bgayx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lly.bigdata.bgayx.common.utils.SecurityUtils;
import com.lly.bigdata.bgayx.common.utils.StringUtils;
import com.lly.bigdata.bgayx.entity.SysUser;
import com.lly.bigdata.bgayx.entity.SysUserRole;
import com.lly.bigdata.bgayx.mapper.SysUserMapper;
import com.lly.bigdata.bgayx.mapper.SysUserRoleMapper;
import com.lly.bigdata.bgayx.service.ISysUserService;
import com.lly.bigdata.bgayx.vo.Result;
import com.lly.bigdata.bgayx.vo.SearchModel;
import com.lly.bigdata.bgayx.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author lly
 * @since 2020-10-21
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询用户角色 用角色代码作为唯一标识
     *
     * @param username
     * @return
     */
    @Override
    public Set<String> getUserRolesSet(String username) {
        List<String> rolecodes = this.baseMapper.getRoleByUserName(username);
        return new HashSet<>(rolecodes);
    }

    /**
     * 查询分页
     *
     * @param searchModel
     * @return
     */
    @Override
    public Result queryPage(SearchModel searchModel) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(searchModel.getS_name())) {
            queryWrapper.like("USERNAME", searchModel.getS_name());
        }
        if (StringUtils.isNotBlank(searchModel.getOrgid())) {
            queryWrapper.eq("orgid", searchModel.getOrgid());
        }
        IPage page = new Page(searchModel.getPageNumber(), searchModel.getPageSize());
        IPage<SysUser> pages = this.baseMapper.selectPage(page, queryWrapper);
        Result res = Result.pageOk(page.getRecords());
        res.setTotal(pages.getTotal());
        res.setPages((long) page.getPages());
        return res;
    }

    /**
     * 用户名获取用户数据
     *
     * @param username
     * @return
     */
    @Override
    public SysUser getUserByName(String username) {
        QueryWrapper q = new QueryWrapper<SysUser>();
        q.eq("username", username);
        SysUser user = this.getOne(q);
        return user;
    }


    @Override
    public Result selectByUserid(String id) {
        SysUser user = this.baseMapper.selectById(id);
        if (user != null) {
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", id);
            List<SysUserRole> list = sysUserRoleMapper.selectList(queryWrapper);
            SysUserVo vo = new SysUserVo();
            BeanUtils.copyProperties(user, vo);
            List<Long> roleids = list.stream().map(v -> v.getRoleId()).collect(Collectors.toList());
            vo.setRoleids(StringUtils.join(roleids, ","));
            Result result = new Result();
            result.setData(vo);
            return result;
        }
        return null;
    }

    @Override
    @Transactional(readOnly = false)
    public Result addUserRole(SysUserVo user, long loginUserId) {
        SysUser sysuser = this.getUserByName(user.getUsername());
        if (sysuser == null) {
            sysuser = new SysUser();
            BeanUtils.copyProperties(user, sysuser);
            sysuser.setCreateTime(LocalDateTime.now());
            sysuser.setStatus(user.getStatus());
            sysuser.setCreateUserId(loginUserId);
            String salt = StringUtils.randomGen(8);
            sysuser.setSalt(salt);
            if (StringUtils.isNotBlank(user.getPassword())) {
                return Result.fail("密码不能为空！");
            }
            if (user.getPassword().length() > 16) {
                return Result.fail("密码长度不能大于16！");
            }
            String password = SecurityUtils.encryptPassword(user.getPassword());
            sysuser.setPassword(password);
            this.baseMapper.insert(sysuser);
            List<String> roles = StringUtils.splitList(user.getRoleids());
            insertUserRole(roles, sysuser.getUserId());
        } else {
            return Result.fail("用户名已存在！");
        }
        return Result.ok();
    }

    private void insertUserRole(List<String> roles, Long userId) {
        roles.forEach(v -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setId(IdWorker.get32UUID());
            sysUserRole.setRoleId(Long.valueOf(v));
            sysUserRole.setUserId(userId);
            sysUserRoleMapper.insert(sysUserRole);
        });
    }

    private void deleteUserRole(Long userid) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userid);
        sysUserRoleMapper.delete(queryWrapper);
    }

    /**
     * 验证用户名
     *
     * @param username
     * @return
     */
    @Override
    public Boolean ckUserName(String username) {

        SysUser user = this.getUserByName(username);
        if (user == null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Result updateUser(SysUserVo vo, Long userid) {
        //user.setUsername(null);//用户名不允许修改
        SysUser user = this.baseMapper.selectById(vo.getUserId());
        if (user != null) {
            String username = user.getUsername();
            String password = user.getPassword();
            LocalDateTime time = user.getCreateTime();
            String salt = user.getSalt();
            BeanUtils.copyProperties(user, vo);
            user.setUsername(username);
            user.setSalt(salt);
            user.setCreateUserId(userid);
            if (StringUtils.isNoneBlank(user.getPassword())) {
                String encode = SecurityUtils.encryptPassword(user.getPassword());
                user.setPassword(encode);
            } else {
                user.setPassword(password);
            }
            user.setCreateTime(time);
            this.baseMapper.updateById(user);
        } else {
            return Result.fail("用户不存在！");
        }
        return Result.ok();
    }

    @Override
    public Result updateUserRole(SysUserVo user, Long loginUser) {
        Result res = updateUser(user, loginUser);
        if (res.getCode() == Result.Code_OK) {
            deleteUserRole(user.getUserId());
            insertUserRole(StringUtils.splitList(user.getRoleids()), user.getUserId());
        } else {
            return Result.fail("用户不存在！");
        }
        return Result.ok();
    }

    @Override
    @Transactional(readOnly = false)
    public void delUser(Long userid) {
        this.baseMapper.deleteById(userid);
        deleteUserRole(userid);
    }

    /**
     * 修改登录信息
     *
     * @param userid
     * @param ip
     * @param date
     */
    @Override
    public void updateUserProfile(Long userid, String ip, Date date) {
        SysUser sysUser = this.baseMapper.selectById(userid);
        sysUser.setLoginIp(ip);
        sysUser.setLoginDate(date);
        baseMapper.updateById(sysUser);
    }
}
